#!/usr/local/bin/python
# -*- coding: utf-8 -*-


'''
商城模块
'''
import logging, traceback
from tornado.escape import json_encode,json_decode

import log
import util
import const
import time
import datetime
import user
from store import store
logger = logging.getLogger(__name__)

#进入商城
def method_enter_store(request,data): 
    tmpSendMsgUtil = util.SendMsgUtil(request)
    if not user.UserManager.set_user_palce(request,"store"):
        tmpSendMsgUtil.update_res("user_is_null")
    tmpSendMsgUtil.send(cmd='enter_store')
    

def method_reload_data(request,data):
    '''管理php后台通知商品数据有修改， 需重新加载进内存，并通知在线客户端'''
    socket_id = request.socket_id
    log.print_debug(logger, "method_reload_data exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "reload_data" 
         
    tmpSendMsgUtil = util.SendMsgUtil(request)  #消息发送器 
    store.instance().reload() #加载商城列表
    
    tmpInfo = ["clothing", "ornament", "present", "furniture", "props"]
    tmpSendMsgUtil.add_item('store', tmpInfo)
    tmpMsg = tmpSendMsgUtil.getEncodeContent()  #编码
    user.UserManager.sendMsgToAll(cmd, tmpMsg)  #给所有在线用户发消息  
    
#购买商品
def method_buy_goods(request,data):   
    socket_id = request.socket_id
    log.print_debug(logger, "method_buy_goods exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "buy_goods"

    data_dict = json_decode(data)
    tmpReqOwnerID = data_dict.get('owner')  #
    tmpReqGoods = data_dict.get('goods')    #
    tmpReqType = data_dict.get('type')    #
        
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpbuyerUser = user.UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpbuyerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    #---判断购买的商品是否有需要特殊处理的道具
    import process_props 
    if not process_props.buyPropsExt(cmd, tmpSendMsgUtil, tmpbuyerUser, tmpReqGoods):
        return

    res = store.buy_goods(request, tmpReqOwnerID, tmpReqGoods)
    if res["res"] != True:
        tmpSendMsgUtil.update_res(res['res'])
        tmpSendMsgUtil.send(cmd)
        return
    else:
        #*** wudi *** start
        isGoodsID = tmpReqGoods[0]['id']    #商品-道具 ID
        isGoodsNum = tmpReqGoods[0]['nums'] #商品-道具  数量
        isGoodsInfo = store.get_goods_info(isGoodsID)
        isGoodsName = isGoodsInfo['goods_name']

        msg = "您获得了 %s %d 个"%(isGoodsName, isGoodsNum)
        msg = '<font color="#FFFF00">%s</font>'%(msg)
        print "@3@>>>", msg
        #*** wudi *** end
        
        tmpSendMsgUtil.add_item("type", tmpReqType)
        tmpSendMsgUtil.add_item("goods",res['goods'])
        tmpSendMsgUtil.add_item("buyer",res['buyer'])
        tmpSendMsgUtil.add_item("owner",res['owner'])
        tmpSendMsgUtil.add_item("msg",msg)  #***wudi***
        
        tmpSendMsgUtil.send(cmd)
        
        if tmpbuyerUser.getUID() != tmpReqOwnerID:
            tmpOwner = user.UserManager.get_user_by_uid(tmpReqOwnerID) 
            if tmpOwner:    #被赠送者在线, 则通知
                tmpSendMsgUtil.send(cmd=cmd, request=tmpOwner.getRequest())
                
            #----通知php, 写信息到文本
            user.UserManager.sendLogFriendInfoUrl(tmpbuyerUser.getUID(), tmpbuyerUser.getNickname(), cmd, tmpReqOwnerID)
                
    
    #首次购买, 则赠送礼物 
    tmpUserRegStep = tmpbuyerUser.getUserInfoToList("reg_step")  #从缓存获取用户注册步骤
    tmpCurrentRegStepName = "first_buy_goods"
    if not tmpbuyerUser.isRegFinish(): 
        bDelete = util.deleteFromList(tmpUserRegStep, tmpCurrentRegStepName)       #删除注册步骤
        if bDelete: #True表示删除成功即第一次走此步骤
            tmpGoodsList = const.Config_reg_send_goods_to_boy()  #从配置文件取得对应的赠送商品列表
            if tmpbuyerUser.getSex()==0:
                tmpGoodsList = const.Config_reg_send_goods_to_girl() 
            store.send_goods_to_somebody(tmpbuyerUser, tmpGoodsList)#送礼, 修改缓存, 修改DB
            
    
#出售商品
def method_sell_goods(request,data):
    data = json_decode(data)
    tmpSendMsgUtil = util.SendMsgUtil(request)
    goods = data.get('goods')
    res = store.sell_goods(request,goods)
    if res["res"] != True:
        tmpSendMsgUtil.update_res(res['res'])  
    else:
        tmpSendMsgUtil.add_item("goods",res['goods'])    
    tmpSendMsgUtil.send(cmd='sell_goods')

#查询商品信息
def method_query_goods(request,data):
    data = json_decode(data)
    goods = data['goods_id']
    goods_info=[]
    for v in goods:
        if v:
            res = store.get_goods_info(v)
            if res:
                goods_info.append(res)
    
    tmpSendMsgUtil = util.SendMsgUtil(request)
    tmpSendMsgUtil.add_item("goods_info",goods_info)    
    tmpSendMsgUtil.send(cmd='query_goods')

#续费商品
def method_renew_goods(request,data):
    data = json_decode(data)
    goods = data['goods']
    res = store.renew_goods(request,goods)
    tmpSendMsgUtil = util.SendMsgUtil(request)
    if res["res"] != True:
        tmpSendMsgUtil.update_res(res['res'])
    else:
        tmpSendMsgUtil.add_item("goods",res['goods'])
    tmpSendMsgUtil.send(cmd='renew_goods')

#查询用购买信息
def method_query_user_goods_list(request,data):
    data = json_decode(data)    
    tmpSendMsgUtil = util.SendMsgUtil(request)
    this_user = user.UserManager.get_user_by_request(request)
    if not this_user:
        return {'res':'user_is_null'}       
    userinfo = this_user.m_userinfo
    uid = userinfo['uid']
    owner = data.get('uid')
    if owner:
        uid = owner
    type_1 = data['type_1']
    type_2 = data['type_2']
    type_3 = data['type_3']
    begin  = data['begin']
    nums   = data['nums']
   
    res = store.get_my_goods_by_type(uid,type_1,type_2,type_3,begin,nums)
    if res["res"] != True:
        tmpSendMsgUtil.update_res(res['res'])
    else:
        tmpSendMsgUtil.add_item("list",res['list'])
        tmpSendMsgUtil.add_item("begin",begin)
        tmpSendMsgUtil.add_item("type_1",type_1)
        tmpSendMsgUtil.add_item("type_2",type_2)  
        tmpSendMsgUtil.add_item("type_3",type_3)
        tmpSendMsgUtil.add_item("uid",uid)
        tmpSendMsgUtil.add_item("count",res['count'])
    tmpSendMsgUtil.send(cmd='query_user_goods_list')

#查询商品数量
def method_query_goods_nums(request,data):
    data = json_decode(data)    
    tmpSendMsgUtil = util.SendMsgUtil(request)
    res = store.get_goods_nums(request,data)
    if res["res"] != True:
        tmpSendMsgUtil.update_res(res['res'])
    else:
        tmpSendMsgUtil.add_item("list",res['list'])
    tmpSendMsgUtil.send(cmd='query_goods_nums')

def method_sendgoods(request,data):
    '''免费给当前用户送礼'''
    socket_id = request.socket_id   
    cmd = "sendgoods" 
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器  
    tmpUser = user.UserManager.get_user_by_request(request)
    data_dict = json_decode(data)
    tmpGoodsList = data_dict.get('goods')
    if tmpGoodsList:        
        store.send_goods_to_somebody(tmpUser, tmpGoodsList)
        tmpSendMsgUtil.add_item("goods", tmpGoodsList)
    tmpSendMsgUtil.send(cmd)

util.registMethod("enter_store", method_enter_store)        #进入商城
util.registMethod("reload_data", method_reload_data)        #通知客户端商城数据有变化
util.registMethod("buy_goods",   method_buy_goods)          #购买商品
util.registMethod("sell_goods",  method_sell_goods)         #出售商品
util.registMethod("query_goods", method_query_goods)        #查询商品信息
util.registMethod("renew_goods", method_renew_goods)        #续费商品
util.registMethod("query_user_goods_list", method_query_user_goods_list)        #查询用户穿着信息
util.registMethod("query_goods_nums", method_query_goods_nums)        #查询用户穿着信息
util.registMethod("sendgoods", method_sendgoods)                         #免费送礼


